package com.siyoumi.app.test.print;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.print.*;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import java.io.ByteArrayInputStream;

@Slf4j
public class testPrint2 {
    @SneakyThrows
    public static void main(String[] args) {
        // 获取默认打印机
        PrintService defaultPrintService = PrintServiceLookup.lookupDefaultPrintService();

        if (defaultPrintService == null) {
            System.out.println("未找到默认打印机");
            return;
        }

        // 创建打印作业属性集合
        HashPrintRequestAttributeSet printAttributes = new HashPrintRequestAttributeSet();

        // 设置打印份数为1（可选）
        printAttributes.add(new Copies(1));

        // 创建文本内容并转换成字节流
        String textContent = "Hello World!";
        byte[] contentBytes = textContent.getBytes();

        // 创建输入流对象
        ByteArrayInputStream inputStream = new ByteArrayInputStream(contentBytes);

        // 创建打印任务
        //DocFlavor docFlavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
        DocFlavor flavor = DocFlavor.STRING.TEXT_PLAIN;

        SimpleDoc simpleDoc = new SimpleDoc(textContent, flavor, null);

        // 提交打印任务
        DocPrintJob job = defaultPrintService.createPrintJob();
        job.print(simpleDoc, printAttributes);

        // 关闭输入流
        inputStream.close();
    }

}
